package com.yuntoyun.fwcore.plug.tool;
/*
 * +----------------------------------------------------------------------
 * | @Author: codeavatar   @Year：2021
 * +----------------------------------------------------------------------
 * | @Email: codeavatar@aliyun.com
 * +----------------------------------------------------------------------
 */
import android.app.Activity;

import com.yuntoyun.fwcore.util.FwLogUtil;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 发送短信(可使用CountDownTimer)
 */
public class FwSmsTool {

    private Activity gActivity;
    private FwSmsToolCallback gCallback;

    private TimerTask timerTask;
    private Timer timer = null;//一次性消耗品
    private int counter = 120;//单位：秒

    public FwSmsTool(Activity activity, FwSmsToolCallback callback) {
        this.gActivity = activity;
        this.gCallback = callback;
    }

    /**
     * 初始化计时器
     */
    public void initTimer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                FwLogUtil.info("FwSmsTool", "计时器运行中...");
                gActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        counter--;
                        gCallback.runTimer(counter);
                        if (counter <= 0) {
                            stopTimer();
                        }
                    }
                });
            }
        };
        gCallback.initTimer();
    }

    /**
     * 开始计时
     */
    public void startTimer() {
        gCallback.startTimer(counter);
        timer.schedule(timerTask, 1000, 1000);//每隔一秒执行一次task中的任务。
    }

    /**
     * 停止计时
     * 注意：必须在Activity中的onDestroy事件中，调用该方法。否则内存泻漏。
     */
    public void stopTimer() {
        if (null != timerTask && null != timer) {
            gCallback.stopTimer();
            if (!timerTask.cancel()) {
                timerTask.cancel();
            }
            timer.cancel();
            timer.purge();
            timer = null;
        }
    }

    public int getCounter() {
        return counter;
    }

    public void setCounter(int counter) {
        this.counter = counter;
    }
}
